//
//  AIBirthdayTableCell.m
//  Mia
//
//  Created by Vill on 2023/12/27.
//

#import "AIBirthdayTableCell.h"
#import "UIView+Gradient.h"

@interface AIBirthdayTableCell ()<UIPickerViewDataSource, UIPickerViewDelegate>

@property (weak, nonatomic) IBOutlet UIView *containView;

@property (nonatomic, strong) UIPickerView   *pickerView;
@property (nonatomic, strong) NSMutableArray *titleArray;
@property (nonatomic, strong) NSMutableArray *yearArray;  // 存储年份的数组
@property (nonatomic, strong) NSMutableArray *monthArray; // 存储月份的数组
@property (nonatomic, strong) NSMutableArray *dayArray;   // 存储日期的数组

@property (nonatomic, assign) NSInteger yearIndex;
@property (nonatomic, assign) NSInteger monthIndex;
@property (nonatomic, assign) NSInteger dayIndex;

@property (nonatomic, assign) NSInteger maxYear;
@property (nonatomic, assign) NSInteger minYear;
@property (nonatomic, strong) UIVisualEffectView *blurView;

@property (nonatomic, strong) UIButton *sureBtn; // 确认

@end

@implementation AIBirthdayTableCell

- (UIVisualEffectView *)blurView{
    if(!_blurView){
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        _blurView.alpha = 0.6;
        _blurView.backgroundColor = [UIColor colorHex:@"#FFFFFF" alpha:0.1];
    }
    return _blurView;
}

-(UIPickerView *)pickerView{
    if(!_pickerView){
        _pickerView = [UIPickerView new];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = UIColor.clearColor;
    }
    return _pickerView;
}

- (NSMutableArray *)titleArray{
    if(!_titleArray){
        _titleArray = [NSMutableArray array];
    }
    return _titleArray;
}

- (NSMutableArray *)yearArray{
    if(!_yearArray){
        _yearArray = [NSMutableArray array];
    }
    return _yearArray;
}

- (NSMutableArray *)monthArray{
    if(!_monthArray){
        _monthArray = [NSMutableArray array];
    }
    return _monthArray;
}

- (NSMutableArray *)dayArray{
    if(!_dayArray){
        _dayArray = [NSMutableArray array];
    }
    return _dayArray;
}

- (UIButton *)sureBtn{
    if(!_sureBtn){
        _sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_sureBtn setImage:KImaged(@"ai_regis_choose_select") forState:UIControlStateNormal];
        _sureBtn.enabled = NO;
//        [_sureBtn setImage:KImaged(@"ai_regis_choose_select") forState:UIControlStateSelected];
        [_sureBtn addTarget:self action:@selector(sureAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sureBtn;
}

// 确认
- (void)sureAction:(UIButton *)sender{
    NSString *selectYear  =  self.yearArray[self.yearIndex];
    NSString *selectMonth =  self.monthArray[self.monthIndex];
    NSString *selectDay   =  self.dayArray[self.dayIndex];
//    NSLog(@"%@--%@--%@",selectYear,selectMonth,selectDay);
    NSString *birth = [NSString stringWithFormat:@"%@%@%@",selectYear,selectMonth,selectDay];
    if (self.selectBirthdayBlock){
        self.selectBirthdayBlock(birth);
    }
}

+(instancetype)cellWithTableView:(UITableView *)tableView{
    static NSString *ID = @"AIBirthdayTableCell";
    AIBirthdayTableCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(cell == nil){
       cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil].lastObject;
    }
    return cell;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    
    self.containView.backgroundColor = [UIColor clearColor];
    self.containView.layer.cornerRadius = PTW(20);
    self.containView.layer.masksToBounds = YES;
    
    [self.containView addSubview:self.blurView];
    [self.blurView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.containView);
    }];
    
    [self.containView addSubview:self.pickerView];
    [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.containView);
    }];
    
    [self.containView addSubview:self.sureBtn];
    [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.trailing.mas_equalTo(self.containView);
        make.size.mas_equalTo(PTW(55));
    }];
    
    self.maxYear =  [NSCalendar.currentCalendar component:NSCalendarUnitYear fromDate:[NSDate date]] - 18;
    self.minYear =  [NSCalendar.currentCalendar component:NSCalendarUnitYear fromDate:[NSDate date]] - 60;
    [self configureYearArray];   //计算年月
//    self.yearIndex = self.yearArray.count / 2 ;
    [self configureMonthArray:12];   //计算月
//    self.monthIndex = self.monthArray.count / 2 ;
    [self configureDayArrayFromYear:[self.yearArray[self.yearIndex] integerValue] andMonth:1];
//    self.dayIndex = self.dayArray.count / 2 ;
//    [self.titleArray addObject:self.yearArray[self.yearIndex]];
//    [self.titleArray addObject:self.monthArray[self.monthIndex]];
//    [self.titleArray addObject:self.dayArray[self.dayIndex]];
//    [self.pickerView selectRow:self.yearArray.count*3/4 inComponent:0 animated:false];
//    [self.pickerView selectRow:0 inComponent:1 animated:false];
//    [self.pickerView selectRow:0 inComponent:2 animated:false];
    [self.titleArray addObject:self.yearArray[0]];
    [self.titleArray addObject:self.monthArray[0]];
    [self.titleArray addObject:self.dayArray[0]];
}

//- (void)drawRect:(CGRect)rect{
//    [super drawRect:rect];
//    [self.containView setGradientBackgroundWithColors:@[[UIColor colorHex:@"#CECECE" alpha:0.2],[UIColor colorHex:@"#CECECE" alpha:0.1],[UIColor colorHex:@"#CECECE" alpha:0.2]] locations:@[@0, @0.5,@1] startPoint:CGPointMake(0.5,0) endPoint:CGPointMake(0.5, 1)];
//}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    // Configure the view for the selected state
}

// 计算年月
- (void)configureYearArray{
    [self.yearArray removeAllObjects];
    for (int i = 0; i<(self.maxYear-self.minYear); i++) {
        NSString *str = [NSString stringWithFormat:@"%ld",(long)(i+self.minYear)];
        [self.yearArray addObject:str];
    }
}

-(void)configureMonthArray:(NSInteger)months{
    [self.monthArray removeAllObjects];
    for (int i = 0; i<months; i++) {
        NSString *str = [NSString stringWithFormat:@"%02d",i+1];
        [self.monthArray addObject:str];
    }
}

-(void)configureDayArrayFromYear:(NSInteger)year andMonth:(NSInteger)month {
    BOOL isRunNian = year % 4 == 0 ? (year % 100 == 0 ? (year % 400 == 0 ? YES : NO) : YES) : NO;
    switch (month) {
        case 1:
        case 3:
        case 5:
        case 7:
        case 8:
        case 10:
        case 12:
            self.dayArray = [self dayArrayWithNumMax:31];
            break;
        case 4:
        case 6:
        case 9:
        case 11:
            self.dayArray = [self dayArrayWithNumMax:30];
            break;
        case 2:
            if (isRunNian) {
                self.dayArray = [self dayArrayWithNumMax:29];
            } else {
                self.dayArray = [self dayArrayWithNumMax:28];
            }
            break;
        default:
            NSLog(@"default 30");
            break;
    }
}

- (NSMutableArray<NSString *> *)dayArrayWithNumMax:(NSInteger)maxNum {
    if (maxNum <=0){return  [NSMutableArray array];}
    NSMutableArray<NSString *> *resultArray = [[NSMutableArray alloc] init];
    for (int i = 1; i < maxNum; i++) {
        NSString *numStr = [NSString stringWithFormat:@"%02d", i];
        [resultArray addObject:numStr];
    }
    return resultArray;
}

- (void)configureDayArrayWithMax:(NSInteger)num {
    self.dayArray = [self dayArrayWithNumMax:num];
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return  50;
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0){
        return self.yearArray.count;
    }else if (component == 1){
        return self.monthArray.count;
    }else{
        return self.dayArray.count;
    }
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    // 设置分割线
//    for (UIView *subview in pickerView.subviews) {
//        if (subview.frame.size.height <= 1) {
//            subview.hidden = NO;
//            subview.frame = CGRectMake(0, subview.frame.origin.y, pickerView.frame.size.width, 1);
//            subview.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.1];
//        }
//    }
    UILabel *pickerLabel = (UILabel *)view;
    if (pickerLabel == nil) {
        pickerLabel = [[UILabel alloc] init];
        pickerLabel.font = [UIFont fontWithWeight:MTBold size:PTW(22)];
        pickerLabel.textAlignment = NSTextAlignmentCenter;
    }
    NSString *title = @"";
    if (component == 0) {
        title = self.yearArray[row];
        pickerLabel.textColor = self.yearIndex == row ? [UIColor whiteColor] : [UIColor colorWithWhite:1 alpha:0.45];
    }
    if (component == 1) {
        title = self.monthArray[row];
        pickerLabel.textColor = self.monthIndex == row ? [UIColor whiteColor] : [UIColor colorWithWhite:1 alpha:0.45];
    }
    if (component == 2) {
        title = self.dayArray[row];
        pickerLabel.textColor = self.dayIndex == row ? [UIColor whiteColor] : [UIColor colorWithWhite:1 alpha:0.45];
    }
    
    pickerLabel.text = title;
    return pickerLabel;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    NSString *title = @"";
    if (component == 0) {
        title = self.yearArray[row];
    }
    if (component == 1) {
        title = self.monthArray[row];
    }
    if (component == 2) {
        title = self.dayArray[row];
    }
    return title;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponents = [calendar components:NSCalendarUnitMonth|NSCalendarUnitDay fromDate:[NSDate date]];
    NSInteger monthArr = dateComponents.month;
    NSInteger dayArr = dateComponents.day;
    if (component == 0) {
        self.yearIndex = row;
        [self.titleArray replaceObjectAtIndex:component withObject:self.yearArray[row]];
    }
    if (component == 1) {
        self.monthIndex = row;
        [self.titleArray replaceObjectAtIndex:component withObject:self.monthArray[row]];
    }
    if (component == 2) {
        self.dayIndex = row;
        [self.titleArray replaceObjectAtIndex:component withObject:self.dayArray[row]];
    }
    // 选中了年去除大于今天的月份  选中了当前年月
    if (self.yearIndex == self.yearArray.count - 1) {
        [self configureMonthArray:monthArr];
        if (self.monthArray.count - 1 < self.monthIndex) {
            self.monthIndex = self.monthArray.count - 1;
        }
        // 月份
        if (self.monthIndex + 1 == self.monthArray.count) {
            [self configureDayArrayWithMax:dayArr];
        } else {
            [self configureDayArrayFromYear:[self.yearArray[self.yearIndex] integerValue] andMonth:[self.monthArray[self.monthIndex] integerValue]];
        }
        
        if (self.monthArray.count - 1 < self.monthIndex) {
            self.monthIndex = self.monthArray.count - 1;
        }
    } else {
        [self configureMonthArray:12];
        [self configureDayArrayFromYear:[self.yearArray[self.yearIndex] integerValue] andMonth:[self.monthArray[self.monthIndex] integerValue]];
        
        if (self.monthArray.count - 1 < self.monthIndex) {
            self.monthIndex = self.monthArray.count - 1;
        }
        if (self.dayArray.count - 1 < self.dayIndex) {
            self.dayIndex = self.dayArray.count - 1;
        }
    }
    [self changeSureBtnValue];
    [pickerView reloadAllComponents];
}

// 更改确认按钮状态
-(void)changeSureBtnValue{

    if ([self.yearArray[self.yearIndex] integerValue] > 0 && [self.monthArray[self.monthIndex] integerValue] > 0 && [self.dayArray[self.dayIndex] integerValue] > 0){
        self.sureBtn.enabled = YES;
    }
}

@end
